package com.erf.handler.client;

import com.erf.handler.server.LoginRequestHandler;
import com.erf.message.ActiveTest;
import com.erf.message.ActiveTestResponse;
import com.erf.message.LoginRequest;
import com.erf.message.LoginRequestResponse;
import com.erf.tools.SequenceUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理登录和心跳响应
 *
 * @author zhangzy
 * @date 2022/7/5
 */
@Slf4j
public class BaseClientChannelDuplexHandler extends ChannelDuplexHandler {

    /**
     * 第一次登录发送
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channel.attr(LoginRequestHandler.KEY).set("zhangzy");
        LoginRequest loginRequest = new LoginRequest("zhangzy", "980980");
        loginRequest.setSequence(SequenceUtil.getSequenceId());
        ctx.writeAndFlush(loginRequest);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof LoginRequestResponse) {
            log.info("[client_receive]" + msg);
            LoginRequestResponse response = (LoginRequestResponse) msg;
            if (response.getCode() == 0) {
                log.info("client:{}登录成功！", ctx.channel().attr(LoginRequestHandler.KEY).get());
            } else {
                String user = ctx.channel().attr(LoginRequestHandler.KEY).get();
                log.info("账号{}登录失败，错误码:{}，描述:{}", user, response.getCode(), response.getDescription());
                ctx.close();
            }
        } else if (msg instanceof ActiveTest) {
            log.info("[client_receive]" + msg);
            ActiveTestResponse activeTestResponse = new ActiveTestResponse();
            activeTestResponse.setSequence(((ActiveTest) msg).getSequence());
            ctx.writeAndFlush(activeTestResponse);
        }
        ctx.fireChannelRead(msg);
    }
}
